package com.qiantu.phone.ui.fragment;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hjq.base.BaseDialog;
import com.hjq.base.FragmentPagerAdapter;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.WeatherInfoBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.TitleBarFragment;
import com.qiantu.phone.bean.WeatherIconBean;
import com.qiantu.phone.event.RefreshHomeDeviceSortSettingEvent;
import com.qiantu.phone.event.RefreshHomeWeatherSettingEvent;
import com.qiantu.phone.event.UpdateFavouriteEvent;
import com.qiantu.phone.scan.ScanCodeActivity;
import com.qiantu.phone.ui.activity.AddDevice1Activity;
import com.qiantu.phone.ui.activity.EditLinkageActivity;
import com.qiantu.phone.ui.activity.EditSceneActivityNew;
import com.qiantu.phone.ui.activity.HomeActivity;
import com.qiantu.phone.ui.activity.MessageCenterActivity;
import com.qiantu.phone.ui.activity.SceneAddGuideActivity;
import com.qiantu.phone.ui.adapter.HomeFragmentPagerAdapter;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.ui.dialog.OptionDialog;
import com.qiantu.phone.utils.WeatherIconParseUtil;
import com.qiantu.phone.widget.ViewPagerScrollIndicator;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

public class HomeNewFragment  extends TitleBarFragment<HomeActivity> {
    private TextView tvDistrict;
    private ImageView ivWeather;
    private TextView tvTemperature;
    private TextView tvHouseName;
    private View topBg;
    private ViewPagerScrollIndicator tabBar;
    //    private View tabShadow;
    private View btnMessage;
    private View btnAdd;
    private ViewPager mViewPager;
    private HomeFragmentPagerAdapter mHomeFragmentPagerAdapter;
    private FloorBean selectedFloor;
    private HashMap<String, String> floorSelectedRoomMap = new HashMap<>();
    private List<RoomBean> selectRooms = new ArrayList<>();
    private int currentAppBarVerticalOffset = -1;
    private XXPermissions xxPermissions;
    private long lastGetWeatherTime;
    //获取天气最小间隔5秒
    private int getWeatherInterval = 300000;

    public static HomeNewFragment newInstance() {
        return new HomeNewFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_new_fragment;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        tvDistrict = findViewById(R.id.tv_district);
        tvTemperature = findViewById(R.id.tv_temperature);
        ivWeather = findViewById(R.id.iv_weather);
        topBg = findViewById(R.id.top_bg);
        tvHouseName = findViewById(R.id.tv_house_name);
        tabBar = findViewById(R.id.tab_bar);
        btnMessage = findViewById(R.id.btn_message);
        btnAdd = findViewById(R.id.btn_add);
        mViewPager = findViewById(R.id.vp_home_pager);
        setOnClickListener(R.id.btn_message, R.id.btn_add);
        mHomeFragmentPagerAdapter = new HomeFragmentPagerAdapter(getChildFragmentManager(), HomeFragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, null);
        mViewPager.setAdapter(mHomeFragmentPagerAdapter);
        updateTopView();
    }

    private void updateTopView() {
        FragmentPagerAdapter<Fragment> mPagerAdapter = new FragmentPagerAdapter<>(this);
        String[] tabs = new String[]{getString(R.string.scene)};
        HomeSubFragment deviceFragment =  HomeSubFragment.newInstance(null, 1);
        mPagerAdapter.addFragment(deviceFragment);
        mViewPager.setAdapter(mPagerAdapter);
        tabBar.setupViewpager(mViewPager);
        tabBar.setTitles(tabs);
    }
    public void initIndex(){
        selectedFloor = null;
        floorSelectedRoomMap.clear();
    }

    private void refreshRoomData() {
        selectRooms.clear();
        if ("favourite".equals(selectedFloor.getFloorSerialNo()) || "common".equals(selectedFloor.getFloorSerialNo())) {
            RoomBean room = new RoomBean();
            room.setRoomSerialNo(selectedFloor.getFloorSerialNo());
            room.setRoomName(selectedFloor.getFloorName());
            selectRooms.add(room);
        } else {
            List<RoomBean> rooms = LLRoomDBManager.getInstance(getContext()).getRoomByFloorSerialNo(selectedFloor.getFloorSerialNo());
            selectRooms.addAll(rooms);
        }
    }

    private HomeSubFragment getHasExistFragment(List<Fragment> fragments, String roomSerialNo, int type){
        for(Fragment fragment : fragments){
            if(fragment instanceof HomeSubFragment){
                HomeSubFragment homeSubFragment = (HomeSubFragment) fragment;
                if((roomSerialNo == null && homeSubFragment.getType() == type)
                        || (roomSerialNo != null && roomSerialNo.equals(homeSubFragment.getRoomSerialNo()))){
                    return homeSubFragment;
                }
            }
        }
        return null;
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddFavouriteEvent(UpdateFavouriteEvent event) {
        updateTopView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshHomeWeatherSettingEvent(RefreshHomeWeatherSettingEvent event) {
        Log.i("lzxlzxlzx", "onRefreshHomeWeatherSettingEvent");
        updateHeaderInfo();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshHomeDeviceSortSettingEvent(RefreshHomeDeviceSortSettingEvent event) {
    }

    /**
     * HomeActivity getAppSetting获取成功后，根据是否显示天气设置再获取天气
     */
    private void updateHeaderInfo(){
        tvHouseName.setText(AppApplication.getInstance().getCurHouseInfo().getName());
        if (AppApplication.getInstance().mSettingBean != null && AppApplication.getInstance().mSettingBean.getSetting().getInterfaceCustomization().isEnvironmentalData()) {
            setWeatherInfo();
        } else {
            if (ivWeather != null) {
                ivWeather.setVisibility(View.GONE);
                tvDistrict.setVisibility(View.GONE);
                tvTemperature.setVisibility(View.GONE);
            }
        }
    }

    private void setWeatherInfo() {
        if (ivWeather != null) {
            if(System.currentTimeMillis() - lastGetWeatherTime > getWeatherInterval) {
                LLHttpManager.getWeather(this,
                        AppApplication.getInstance().getCurHouseInfo().getLongitude(),
                        AppApplication.getInstance().getCurHouseInfo().getLatitude(),
                        new HttpCallback<HttpData<WeatherInfoBean>>(null) {
                            @Override
                            public void onStart(Call call) {
                                super.onStart(call);
                            }

                            @Override
                            public void onSucceed(HttpData<WeatherInfoBean> result) {
                                super.onSucceed(result);
                                tvDistrict.setText(AppApplication.getInstance().getCurHouseInfo().getDistrict());
                                ivWeather.setVisibility(View.VISIBLE);
                                tvDistrict.setVisibility(View.VISIBLE);
                                tvTemperature.setVisibility(View.VISIBLE);
                                if (result.getData() != null) {
                                    WeatherIconBean weatherIcon = WeatherIconParseUtil.getIcon(getActivity(), result.getData().getWeatherCode());
                                    if (weatherIcon != null){
                                        ivWeather.setImageResource(getResources().getIdentifier(weatherIcon.getImage(), "mipmap", AppApplication.getInstance().getPackageName()));
                                    }
                                    if (!TextUtils.isEmpty(result.getData().getTemperatureC())) {
                                        tvTemperature.setText(result.getData().getTemperatureC() + "°c");
                                    }
                                }
                            }

                            @Override
                            public void onFail(Exception e) {
                                super.onFail(e);
                            }

                            @Override
                            public void onEnd(Call call) {
                                super.onEnd(call);
                            }
                        });
            }
            lastGetWeatherTime = System.currentTimeMillis();
        }
    }

    @Override
    protected void initData() {
        updateHeaderInfo();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_message:
                startActivity(MessageCenterActivity.class);
                break;
            case R.id.btn_add:
                showOptionDialog(btnAdd);
                break;
        }
    }

    private OptionDialog optionDialog;

    private void showOptionDialog(View atView) {
        if (optionDialog == null) {
            List<OptionDialog.Option> options = new ArrayList<>();
            options.add(new OptionDialog.Option(R.attr.icon_home_scancode, "扫一扫"));
            options.add(new OptionDialog.Option(R.attr.icon_home_adddevice, "添加设备"));
            options.add(new OptionDialog.Option(R.attr.icon_home_addscenes, "添加场景"));
            options.add(new OptionDialog.Option(R.attr.icon_home_addlinkage, "添加联动"));
            optionDialog = new OptionDialog(getContext())
                    .setOptions(options).setListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                            optionDialog.dismiss();
                            Intent intent = null;
                            switch (position) {
                                case 0:
                                    if (xxPermissions == null) {
                                        xxPermissions = XXPermissions.with(getActivity());
                                    }
                                    String[] permissions = new String[]{
                                            Manifest.permission.CAMERA
                                    };

                                    if(!XXPermissions.isGranted(getContext(),permissions) && AppApplication.isHuawei() ){
                                        showConfirmHintDialog("App需要使用您的相机权限，来扫描TLC1上的二维码，以进行后续的设备添加功能。如若已拒绝，再使用本功能前请先前往手机设置中将本应用的相机权限改为允许。");
                                    }else{
                                        requestPermission();
                                    }
                                    break;
                                case 1:
                                    intent = new Intent(getContext(), AddDevice1Activity.class);
                                    startActivity(intent);
                                    break;
                                case 2:
                                    startActivity(SceneAddGuideActivity.class);
                                    break;
                                case 3:
                                    startActivity(EditLinkageActivity.class);
                                    break;
                            }
                        }
                    });
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .atView(atView)
                    .offsetX(getResources().getDimensionPixelSize(R.dimen.dp_10))
                    .asCustom(optionDialog);
        }
        optionDialog.show();
    }

    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder;

    private void showConfirmHintDialog(String text) {
        if (mConfirmHintDialog == null) {
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(getActivity())
                    .setRightBtnText(getString(R.string.ok))
                    .setListener(new ConfirmHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                            finish();
                        }

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            requestPermission();
                        }
                    });
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
        mConfirmHintDialogBuilder.setCancelable(false);
//        mConfirmHintDialogBuilder.setCanceledOnTouchOutside(false);
        mConfirmHintDialogBuilder.setContent(text);
        mConfirmHintDialog.show();
    }

    private void requestPermission(){
        xxPermissions.permission(Manifest.permission.CAMERA)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            Intent intent = new Intent(getContext(), ScanCodeActivity.class);
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        ToastUtils.show(R.string.common_permission_fail_1);
                    }
                });
    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isHidden()) {
            if (currentAppBarVerticalOffset == 0 || currentAppBarVerticalOffset == -1) {
                getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarChangeIsDarkFont)).init();
            } else {
                getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarIsDarkFont)).init();
            }
        }
        if(AppApplication.getInstance().getCurHouseInfo().getRoleType() == 2){
            btnAdd.setVisibility(View.GONE);
            btnMessage.setVisibility(View.GONE);
        }else{
            btnAdd.setVisibility(View.VISIBLE);
            btnMessage.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!isHidden()) {
            if (currentAppBarVerticalOffset == 0 || currentAppBarVerticalOffset == -1) {
                getAttachActivity().getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarChangeIsDarkFont)).init();
            } else {
                getAttachActivity().getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarIsDarkFont)).init();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        mViewPager.setAdapter(null);
    }
}
